package com.example.demo.saToken.controller;

import cn.dev33.satoken.exception.DisableServiceException;
import cn.dev33.satoken.exception.NotHttpBasicAuthException;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.exception.NotSafeException;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @ClassName GlobalException
 * @Description 全局异常处理
 * @Author MingChang.Wei
 * @Date 2024/9/19
 **/
@RestControllerAdvice
public class GlobalException {
    
    private static final Log log = LogFactory.get();
    
    @ExceptionHandler(NotLoginException.class)
    public SaResult handlerException(NotLoginException e) {
        log.warn("用户未登录访问受保护资源，异常类型: {}", e.getType());
        return SaResult.error("请先登录");
    }

    @ExceptionHandler(NotPermissionException.class)
    public SaResult handlerException(NotPermissionException e) {
        log.warn("用户权限不足，缺少权限: {}", e.getPermission());
        return SaResult.error("权限不足，缺少权限：" + e.getPermission());
    }

    @ExceptionHandler(NotRoleException.class)
    public SaResult handlerException(NotRoleException e) {
        log.warn("用户角色不足，缺少角色: {}", e.getRole());
        return SaResult.error("角色不足，缺少角色：" + e.getRole());
    }

    @ExceptionHandler(NotSafeException.class)
    public SaResult handlerException(NotSafeException e) {
        log.warn("二级认证校验失败，服务: {}", e.getService());
        return SaResult.error("二级认证校验失败");
    }

    @ExceptionHandler(DisableServiceException.class)
    public SaResult handlerException(DisableServiceException e) {
        log.warn("账号服务被封禁，服务: {}, 等级: {}, 封禁时间: {}秒", 
                e.getService(), e.getLevel(), e.getDisableTime());
        return SaResult.error("当前账号服务已被封禁，" + e.getDisableTime() + "秒后解封");
    }

    @ExceptionHandler(NotHttpBasicAuthException.class)
    public SaResult handlerException(NotHttpBasicAuthException e) {
        log.warn("HTTP Basic认证失败: {}", e.getMessage());
        return SaResult.error("认证失败");
    }

    @ExceptionHandler(Exception.class)
    public SaResult handlerException(Exception e) {
        log.error("系统发生未知异常", e);
        return SaResult.error("系统异常，请联系管理员");
    }
}
